package top.kaoshanji.p1ch07a;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.stream.Stream;

/**
 * author kaoshanji
 * ^_^
 * create time 2025/2/13 09:44
 */
public class ParallelStreams {

    private static final Logger logger = LogManager.getLogger(ParallelStreams.class);

    public static void main(String[] args) {

        // 代码清单-p1ch07a-152页a：顺序归约计算所有数字的和
        logger.info("...顺序归约计算所有数字的和...");
        System.out.println(sequentialSum(112));


        // 代码清单-p1ch07a-152页b：迭代式计算所有数字的和
        logger.info("...迭代式计算所有数字的和...");
        System.out.println(iterativeSum(112));


        // 代码清单-p1ch07a-152页c：并行归约计算所有数字的和
        logger.info("...并行归约计算所有数字的和...");
        System.out.println(parallelSum(112));

    }

    private static long sequentialSum(long n) {
        return Stream.iterate(1L, i -> i + 1).limit(n).reduce(Long::sum).get();
    }

    private static long iterativeSum(long n) {
        long result = 0;
        for (long i = 0; i <= n; i++) {
            result += i;
        }
        return result;
    }

    private static long parallelSum(long n) {
        return Stream.iterate(1L, i -> i + 1).limit(n).parallel().reduce(Long::sum).get();
    }




}
